﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Diagnostics;

public partial class Documents_UploadDocuments_ShowFile : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string fileName = Request.QueryString["n"];
        string contentType = Request.QueryString["t"];

        if (!string.IsNullOrEmpty(fileName))
        {
            UploadFile file = new UploadFile(fileName, contentType);

            if (file.Exists())
            {
                Response.ContentType = file.ContentType;
                Response.AddHeader("Content-Disposition", "attachment;filename=\"" + file.FilePath + "\"");
                Response.AddHeader("Content-Size", file.ContentSize.ToString());
                Response.BinaryWrite(file.GetContent());
                file.Dispose();
                Response.End();
            }
            else
            {
                this.lblError.Text = "Файлът не съществува!";
            }
        }
    }
}

public class UploadFile 
{
    private string filePath;
    private string contentType;
    private long contentSize;
    private FileStream fileStream;

    public UploadFile(string filePath, string contentType)
    {
        this.filePath = filePath;
        this.contentType = contentType;
    }

    public string FilePath
    {
        get { return this.filePath; }
        set { this.filePath = value; }
    }

    public string ContentType
    {
        get { return this.contentType; }
        set { this.contentType = value; }
    }

    public long ContentSize
    {
        get { return this.contentSize; }
        set { this.contentSize = value; }
    }

    public FileStream FileStream
    {
        get { return this.fileStream; }
        set { this.fileStream = value; }
    }

    public byte[] GetContent()
    {
        byte[] buff = null;

        this.FileStream = new FileStream(this.filePath, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(this.FileStream);
        long numBytes = new FileInfo(this.filePath).Length;
        buff = br.ReadBytes((int)numBytes);

        return buff;
    }

    public void Dispose()
    {
        this.FileStream.Dispose();
    }

    public bool Exists()
    {
        return new FileInfo(this.FilePath).Exists;
    }
}
